<?php

namespace Core\http;


class Response
{
    /**
     * @var \Swoole\Http\Response
     */
    protected $swooleResponse;

    /**
     * @var
     */
    protected $body;

    /**
     * Response constructor.
     * @param \Swoole\Http\Response $swooleResponse
     */
    public function __construct(\Swoole\Http\Response $swooleResponse)
    {
        $this->swooleResponse = $swooleResponse;

        //设置默认头
        $this->setHeader("Content-Type", "text/html; charset=utf-8");
    }

    /**
     * 初始化
     * @param \Swoole\Http\Response $swooleResponse
     * @return Response
     */
    public static function init(\Swoole\Http\Response $swooleResponse)
    {
        return new self($swooleResponse);
    }

    /**
     * 设置头信息
     * @param $k
     * @param $v
     */
    public function setHeader($k, $v)
    {
        $this->swooleResponse->setHeader($k, $v);
    }

    public function setHttpStatus(int $status)
    {
        $this->swooleResponse->setStatusCode($status);
    }

    public function redirect($url, int $code = 301)
    {
        //使用这个不会报错了
        $this->swooleResponse->redirect($url, $code);

        //另一种写法：
//        $this->setHttpStatus($code);
//        $this->setHeader('Location', $url);
    }

    /**
     * @return mixed
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * @param mixed $body
     */
    public function setBody($body): void
    {
        $this->body = $body;
    }

    /**
     * 测试输出
     * @param $html
     */
    public function writeHtml($html)
    {
        $this->swooleResponse->write($html);
    }

    /**
     * 结束响应并输出
     */
    public function end()
    {
        $json_covert = ['array', 'object'];

        $body = $this->getBody();
        if (in_array(gettype($body), $json_covert)) {
            $this->setHeader("Content-Type", "application/json;charset=utf-8");
            $this->swooleResponse->write(json_encode($body));
        } else {
            $this->swooleResponse->write($body);
        }

        $this->swooleResponse->end();
    }

}